package com.qiezi.project.fragment;



import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.drawee.view.SimpleDraweeView;
import com.qiezi.App;
import com.qiezi.R;
import com.qiezi.base.BaseMvpActivity;
import com.qiezi.base.BaseMvpFragment;
import com.qiezi.base.BaseRecyclerAdapter;
import com.qiezi.bean.DataType;
import com.qiezi.bean.SiteBean;
import com.qiezi.bean.VideoBean;
import com.qiezi.mvp.CreatePresenter;
import com.qiezi.project.activity.RecyListActivity;
import com.qiezi.project.activity.PlayActivity;
import com.qiezi.project.activity.WebActivity;
import com.qiezi.project.adapter.DomesticAdapter;
import com.qiezi.project.adapter.RecommendAdapter;
import com.qiezi.project.adapter.SiteAdapter;
import com.qiezi.project.contract.VideoContract;
import com.qiezi.project.decoration.RecyclerItemDecoration;
import com.qiezi.project.enums.FooterText;
import com.stx.xhb.xbanner.XBanner;
import com.stx.xhb.xbanner.entity.SimpleBannerInfo;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


@CreatePresenter(presenter = VideoContract.Presenter.class)
public class RecyListFragment extends BaseMvpFragment<VideoContract.Presenter> implements VideoContract.View,SwipeRefreshLayout.OnRefreshListener  {

    public enum HomePageType{
        home(0),domestic(1),newest(2),ranking(3),domesticRecommend(4),jsRecommend(5),eaRecommend(6),site(7);

        private Integer number;
        HomePageType(int number){
            this.number = number;
        }

        public Integer getNumber() {
            return number;
        }
    }


    @BindView(R.id.rcv)
    RecyclerView rcv;

    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;

    private int id;

    public void setId(int id) {
        this.id = id;
    }


    BaseRecyclerAdapter adapter;


    private int page = 1;

    XBanner ivBanner;

    private boolean isLoad = false;

    private HomePageType type;

    public RecyListFragment setType(HomePageType type) {
        this.type = type;
        return this;
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        if (savedInstanceState == null)return;
        savedInstanceState.putInt("type",type.getNumber());
        savedInstanceState.putBoolean("isload",isLoad);
        savedInstanceState.putInt("page",page);
        savedInstanceState.putParcelableArrayList("data",adapter.getData());
    }

    @Override
    public void onResume() {
        startBanner();
        super.onResume();
    }

    public void startBanner(){

        if (ivBanner != null)
            ivBanner.startAutoPlay();
    }

    public void stopBanner(){
        if (ivBanner != null)
            ivBanner.stopAutoPlay();
    }

    @Override
    public void onStop() {
        stopBanner();
        super.onStop();
    }

    @Override
    public int getLayoutRes() {
        if (type == HomePageType.site) return R.layout.fragment_site;
        return R.layout.fragment_single_recy;
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (savedInstanceState != null){
            int n = savedInstanceState.getInt("type");
            type = HomePageType.values()[n];
            isLoad = savedInstanceState.getBoolean("isload");
            page = savedInstanceState.getInt("page");
        }
        if (type.getNumber() == 1 || (type.getNumber()>3 && type.getNumber()<7)){
            GridLayoutManager manager = new GridLayoutManager(getActivity(),2);
            rcv.setLayoutManager(manager);
            adapter = new DomesticAdapter();
            rcv.addItemDecoration(new RecyclerItemDecoration(10,2));
        }else if (type.getNumber() == 7){
            rcv.setLayoutManager(new GridLayoutManager(getActivity(),4));
            adapter = new SiteAdapter();
            rcv.addItemDecoration(new RecyclerItemDecoration(10,4));
            isLoadMore = false;
        }else{
            rcv.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
            adapter = new RecommendAdapter();
            rcv.addItemDecoration(new RecyclerItemDecoration(10,1));
        }
        if (type == HomePageType.home)
            adapter.setHeaderView(getBanner());

        adapter.setEmptyViewDef(getActivity(),R.drawable.ic_network_error);
        adapter.setFooterViewDef((BaseMvpActivity) getActivity());
        rcv.setAdapter(adapter);
        rcv.setItemAnimator(new DefaultItemAnimator());
        refresh.setColorSchemeResources(R.color.colorRed);
        refresh.setOnRefreshListener(this);

        if (savedInstanceState != null){
            log("读取状态");
            adapter.setDatas((ArrayList) savedInstanceState.getSerializable("data"));
            ArrayList list = (ArrayList) savedInstanceState.getSerializable("data");
            log(list);
        }else {
            refresh.setRefreshing(true);
            onRefresh();
        }
    }



    private XBanner getBanner(){
        if (ivBanner != null) return ivBanner;
        ivBanner = new XBanner(getActivity());
        RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,dip2px(130));
        ivBanner.setLayoutParams(params);
        ivBanner.setAutoPalyTime(6000);
        ivBanner.setBackgroundResource(R.color.colorDef);
        ivBanner.setPointPosition(XBanner.RIGHT);
        ivBanner.setShowIndicatorOnlyOne(false);
        ivBanner.setPageChangeDuration(1000);
        ivBanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                SimpleDraweeView v = view.findViewById(R.id.sd_banner);
                Uri uri = Uri.parse(((BannerInfo) model).url);
                v.setImageURI(uri);
            }
        });
        return ivBanner;
    }





    @Override
    public void scrollToTop() {
        if (rcv != null)
            rcv.scrollToPosition(0);
    }



    @Override
    protected void initListener() {
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                if (data instanceof VideoBean){
                    VideoBean video = (VideoBean) data;
                    Intent intent;
                    if (video.getTypedata() == DataType.video){
                        intent = new Intent(getActivity(),PlayActivity.class);
                    }else {
                        intent = new Intent(getActivity(),WebActivity.class);
                    }
                    intent.putExtra("data",video);
                    startActivity(intent);

                }else if (data instanceof SiteBean){
                    SiteBean siteBean = (SiteBean) data;
                    Intent intent = new Intent(getActivity(),RecyListActivity.class);
                    intent.putExtra("data",siteBean);
                    intent.putExtra("type",1);
                    startActivity(intent);
                }
            }

        });


        if (isLoadMore ){
            rcv.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);

                }

                private boolean isLittle = false;
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (!isLittle){
                        isLittle = !(recyclerView.getLayoutManager().getChildCount() == recyclerView.getLayoutManager().getItemCount());
                    }
                    if (isLittle && isLoad && footerText != FooterText.loading && footerText != FooterText.notMore) {
                        if (App.getInstance().isVip){
                            if (isSlideToBottom(rcv)){
                                setFooterText(FooterText.loading);
                                getPresenter().loadMore(++page);
                            }else if (footerText != FooterText.loadMore){
                                setFooterText(FooterText.loadMore);
                            }
                        }else if (footerText != FooterText.notVip){
                            setFooterText(FooterText.notVip);
                        }
                    }
                }
            });
        }

    }

    private boolean isLoadMore = true;


    public void complete(FooterText status){


        setFooterText(status);
        complete();

    }


    @Override
    public void onCanceled() {
        super.onCanceled();
        getPresenter().canceledCell();
    }

    @Override
    public void complete() {
        super.complete();
        log("complete");
        isLoad = true;
        if (refresh != null && refresh.isRefreshing()){
            refresh.setRefreshing(false);
        }
        if (adapter.getEmptyVisibility() == View.INVISIBLE){
            adapter.setEmptyVisibility(View.VISIBLE);
        }

    }

    @Override
    public void showError(String msg) {
        super.showError(msg);
        adapter.setEmptyImage(R.drawable.ic_network_error);
        complete(FooterText.loadError);
    }

    private FooterText footerText = FooterText.notMore;

    private void setFooterText(FooterText ft){
        footerText = ft;
        adapter.setFooterText(ft.getString());
    }

    @Override
    public void onLoadMore(ArrayList data, List<String> banners) {
        if (data.size() == 0){
            complete(FooterText.notMore);
        }else {
            adapter.addDatas(data);
            complete(FooterText.complete);
        }
    }

    @Override
    public HomePageType getType() {
        return type;
    }

    public static class BannerInfo extends SimpleBannerInfo {

        private String url;

        public BannerInfo(String url){
            this.url = url;
        }

        @Override
        public Object getXBannerUrl() {
            return url;
        }
    }

    @Override
    public void onRefresh(ArrayList data, List<String> banners) {
        if (data.size() == 0){
            adapter.setEmptyImage(R.drawable.ic_data_empty);
        }
        if (type == HomePageType.home){
            if (banners != null && banners.size()>0){
                ArrayList<SimpleBannerInfo> list = new ArrayList<>();
                for (String url : banners){
                    list.add(new BannerInfo(url));
                }
                ivBanner.setBannerData(R.layout.item_banner,list);
            }
        }

        adapter.setDatas(data);
        complete(FooterText.empty);
    }




    @Override
    public void onRefresh() {
        page = 1;
        getPresenter().loadData(page);
    }
}
